package com.dkm.ec.sale.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dkm.base.api.model.Page;
import com.dkm.base.core.util.string.StringUtils;
import com.dkm.biz.gl.persistence.entity.EavSetAttrPo;
import com.dkm.biz.gl.persistence.entity.GlCatePo;
import com.dkm.biz.gl.persistence.entity.GlConfigPo;
import com.dkm.biz.gl.repository.EavSetAttrRepository;
import com.dkm.biz.gl.repository.GlCateRepository;
import com.dkm.biz.gl.repository.GlConfigRepository;
import com.dkm.biz.gl.service.EavAttrService;
import com.dkm.biz.ou.domain.Party;
import com.dkm.biz.ou.repository.PartyRepository;
import com.dkm.ec.product.persistence.entity.ProdCatePo;
import com.dkm.ec.product.persistence.entity.ProductMediaPo;
import com.dkm.ec.product.repository.ProdCateRepository;
import com.dkm.ec.product.repository.ProductMediaRepository;
import com.dkm.ec.sale.domain.SaleConstants;
import com.dkm.ec.sale.domain.SaleEntity;
import com.dkm.ec.sale.persistence.dao.SaleSkuQueryDao;
import com.dkm.ec.sale.persistence.entity.SaleEntityStatPo;
import com.dkm.ec.sale.persistence.entity.SalePricePo;
import com.dkm.ec.sale.persistence.entity.SaleSkuPo;
import com.dkm.ec.sale.persistence.entity.SaleSkuTagPo;
import com.dkm.ec.sale.repository.SaleEntityRepository;
import com.dkm.ec.sale.repository.SaleEntityStatRepository;
import com.dkm.ec.sale.repository.SalePriceRepository;
import com.dkm.ec.sale.repository.SaleSkuRepository;
import com.dkm.ec.sale.repository.SaleSkuTagRepository;
import com.dkm.ec.sale.service.SaleSkuService;
@Service
public class SaleSkuServiceImpl implements SaleSkuService{
	@Resource
	private SaleSkuQueryDao saleSkuQueryDao;
	@Resource
	private SaleSkuRepository saleSkuRepository;
	@Resource
	private SaleEntityRepository saleEntityRepository;
	@Resource
	private EavSetAttrRepository eavSetAttrRepository;
	@Resource
	private ProductMediaRepository productMediaRepository;
	@Resource
	private GlConfigRepository glConfigRepository;
	@Resource
	private SaleEntityStatRepository saleEntityStatRepository;
	@Resource
	private GlCateRepository glCateRepository;
	@Resource
	private SaleSkuTagRepository saleSkuTagRepository;
	@Resource
	private ProdCateRepository prodCateRepository;
	@Resource
	private SalePriceRepository salePriceRepository;
/*	@Resource
	private PromotionService promotionService;
	@Resource
	private  SaleReviewRepository saleReviewRepository;*/
	@Resource
	private PartyRepository partyRepository;
	
	
	
	@Resource
	private EavAttrService eavAttrService;
	@Override
	public SaleSkuPo getSaleSkuPoById(String id) {
		return saleSkuQueryDao.get(id);
	}
	@Override
	public SaleSkuPo getSaleSkuPoDetailById(String key, String callType) {
		SaleSkuPo saleSkuPo = getSaleSkuPoById(key);
		//获取产品
		SaleEntity saleEntity = saleEntityRepository.load(saleSkuPo.getSaleProdId());	
		//获取saleEntity普通属性
		if(StringUtils.isNotEmpty(saleEntity.getData().getEavSetKey())){
					saleSkuPo.getSaleEntityPo().setAttrDataMap(eavAttrService.getAttrValuesNoSkuByProdSetKey(saleSkuPo.getSaleEntityPo().getId(), saleEntity.getData().getEavSetKey()));	
		}
		//获取media
		//获取SKU的首图 获取图片大小 
		if(StringUtils.isNotEmpty(saleEntity.getData().getEavSetKey())){
			//获取sku主sku属性对应的optionid
			EavSetAttrPo eavSetAttrPo = eavSetAttrRepository.getMainSkuAttrBySetKey(saleEntity.getData().getEavSetKey());
			String[] attrList = saleSkuPo.getAttrIds().split(",");
			String attrOpId = "";
			for(int i=0;i<attrList.length;i++){
				if(eavSetAttrPo!=null&&eavSetAttrPo.getAttrId()!=null&&eavSetAttrPo.getAttrId().equals(attrList[i])){
					String[] attrOps = saleSkuPo.getAttrOpIds().split(",");
					attrOpId = attrOps[i];
					break;
				}
			}
			if(StringUtils.isNotEmpty(attrOpId)){
				ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdIdAttrOpId(saleEntity.getData().getId(),attrOpId);//
				saleSkuPo.setMainCloudPath(productMediaPo.getCloudPath());	
			}
			
		}else{
			ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdId(saleEntity.getData().getId());
			if(productMediaPo!=null) saleSkuPo.setMainCloudPath(productMediaPo.getCloudPath());
		}
		//获取glconfig中设置的图片缩放比率
		GlConfigPo glConfigPo = glConfigRepository.getByConfigKey("mainProductMediaSize");
		saleSkuPo.setImgSizeMap(glConfigPo.getOptionsMap(callType));
		//获取sku所在产品对应的所有sku
		List<SaleSkuPo> skuPos = saleSkuQueryDao.findByProdId(saleEntity.getData().getId());
		saleEntity.getData().setSaleSkuPos(skuPos);
		
		
		return saleSkuPo;
	}
	@Override
	public void getSkuName(SaleSkuPo saleSkuPo) {
		if(StringUtils.isEmpty(saleSkuPo.getSkuName())){
			if(saleSkuPo.getSaleEntityPo()!=null){
				saleSkuPo.setSkuName(saleSkuPo.getSaleEntityPo().getName());
			}else{
				SaleEntity saleEntity = saleEntityRepository.load(saleSkuPo.getSaleProdId());
				if(saleEntity!=null)saleSkuPo.setSkuName(saleEntity.getData().getName());		
			}
		}
	}
	@Override
	public String getSkuNameById(String prodId, String name) {
		if(StringUtils.isEmpty(name)){
			SaleEntity saleEntity = saleEntityRepository.load(prodId);
			if(saleEntity!=null)name = saleEntity.getData().getName();
		}
		return name;
	}
	
	@Override
	public String getMainProdCloudPath(String skuId, String callType,String picType) {
		SaleSkuPo saleSkuPo = saleSkuQueryDao.get(skuId);
		getMainProdCloudPath(saleSkuPo, callType,picType);
		return saleSkuPo.getMainCloudPath();
	}
	@Override
	public void getMainProdCloudPath(SaleSkuPo saleSkuPo, String callType,String picType) {
		if(saleSkuPo.getSaleEntityPo()==null){
			SaleEntity saleEntity = saleEntityRepository.load(saleSkuPo.getSaleProdId());
			if(saleEntity!=null)saleSkuPo.setSaleEntityPo(saleEntity.getData());			
		}
		if(saleSkuPo.getSaleEntityPo()!=null){
			ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdId(saleSkuPo.getSaleEntityPo().getSaleId());//
			if(productMediaPo!=null){
				saleSkuPo.setMainCloudPath(setImgUrlWithSize(productMediaPo.getCloudPath(),callType,picType));	
			} 
		}
		
	}
	@Override
	public String getMainSkuCloudPath(String skuId, String callType,String picType) {
		SaleSkuPo saleSkuPo = saleSkuQueryDao.get(skuId);
		getMainSkuCloudPath(saleSkuPo,callType,picType);
		return saleSkuPo.getMainSkuCloudPath();
	}
	@Override
	public void getMainSkuCloudPath(SaleSkuPo saleSkuPo, String callType,String picType) {
		//获取产品
				SaleEntity saleEntity = saleEntityRepository.load(saleSkuPo.getSaleProdId());	
				String attrOpId = "";
				if(saleEntity!=null){
					if(StringUtils.isNotEmpty(saleEntity.getData().getEavSetKey())){
						//获取sku主sku属性对应的optionid
						EavSetAttrPo eavSetAttrPo = eavSetAttrRepository.getMainSkuAttrBySetKey(saleEntity.getData().getEavSetKey());
						String[] attrList = {};
						String  attrIdsStr= saleSkuPo.getAttrIds();
						if(attrIdsStr!=null){
							attrList = attrIdsStr.split(",");
						}						
						//String[] attrList = saleSkuPo.getAttrIds().split(",");
						for(int i=0;i<attrList.length;i++){
							if(eavSetAttrPo!=null&&eavSetAttrPo.getAttrId()!=null&&eavSetAttrPo.getAttrId().equals(attrList[i])){
								String[] attrOps = {};
								String  attrOpIds= saleSkuPo.getAttrOpIds();
								if(attrIdsStr!=null){
									attrOps = attrOpIds.split(",");
								}										
								//String[] attrOps = saleSkuPo.getAttrOpIds().split(",");
								attrOpId = attrOps[i];
								break;
							}
						}
					}
					//if(StringUtils.isNotEmpty(attrOpId)){
					if(saleEntity.getData()!=null){
						ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdIdAttrOpId(saleEntity.getData().getId(),attrOpId);//
						if(productMediaPo!=null){
							saleSkuPo.setMainSkuCloudPath(setImgUrlWithSize(productMediaPo.getCloudPath(),callType,picType));	
							saleSkuPo.setMainCloudPath(saleSkuPo.getMainSkuCloudPath());
						}	
					}
					else{
						saleSkuPo.setMainSkuCloudPath("");	
						saleSkuPo.setMainCloudPath("");
					}
					
					//}
				}
				
				
	}
	
	private String setImgUrlWithSize(String url,String callType,String picType){
		if(StringUtils.isNotEmpty(url)){
			GlConfigPo glConfigPo = glConfigRepository.getByConfigKey("mainProductMediaSize");
			String imgSize = glConfigPo.getImgSize(callType,picType);
			url = url + imgSize;	
	
		}
		return url;
	}
	
	/*
	 *获取SKU所有信息给Solr调用 
	 */
	public void  getSaleSkuForSolr( SaleSkuPo saleSkuPo){
		String prodId = saleSkuPo.getSaleProdId();
		SaleEntity saleEntity = saleEntityRepository.load(prodId);
		//获取产品非SKU属性
		if(StringUtils.isNotEmpty(saleEntity.getData().getEavSetKey())){
			saleEntity.getData().setAttrDataMap(eavAttrService.getAttrValuesNoSkuByProdSetKey(prodId, saleEntity.getData().getEavSetKey()));	
		}
		//获取父分类的key
		GlCatePo glCatePo = glCateRepository.getCatePoByChild(saleEntity.getData().getCateKey());
		if(glCatePo!=null){
			saleEntity.getData().setPcid(glCatePo.getParentKey());	
		}
		List<SaleSkuPo> saleSkuPoList = saleSkuQueryDao.findByProdId(saleEntity.getData().getSaleId());
		Integer saleSkuIndex =0;
		saleSkuPo.setIsDefault("N");
		for(SaleSkuPo saleSkuPo2:saleSkuPoList){
			if(saleSkuPo2.getId().equals(saleSkuPo.getId())){
				saleSkuPo.setIsDefault("Y");
				saleSkuIndex++;
				break;
			}
		}
		saleSkuPo.setSaleEntityPo(saleEntity.getData());//saleentitypo 中包含抽象表，分类，属性
		//获取SKU的首图 
		if(StringUtils.isNotEmpty(saleEntity.getData().getEavSetKey())){
			//获取sku主sku属性对应的optionid
			EavSetAttrPo eavSetAttrPo = eavSetAttrRepository.getMainSkuAttrBySetKey(saleEntity.getData().getEavSetKey());
			String[] attrList = {};
			String  attrIdsStr= saleSkuPo.getAttrIds();
			if(attrIdsStr!=null){
				attrList = attrIdsStr.split(",");
			}
			//String[] attrList = saleSkuPo.getAttrIds().split(",");
			String attrOpId = "";
			for(int i=0;i<attrList.length;i++){
				if(eavSetAttrPo!=null&&eavSetAttrPo.getAttrId()!=null&&eavSetAttrPo.getAttrId().equals(attrList[i])){
					String[] attrOps = saleSkuPo.getAttrOpIds().split(",");
					attrOpId = attrOps[i];
					break;
				}
			}
			if(StringUtils.isNotEmpty(attrOpId)){
				ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdIdAttrOpId(prodId,attrOpId);//
				saleSkuPo.setProductMediaPo(productMediaPo);
				//productMediaPo = productMediaRepository.getSpecialMediaPoByProdIdAttrOpId(prodId,attrOpId);
				//if(productMediaPo!=null) {
				//	saleSkuPo.setMainCloudPath(productMediaPo.getCloudPath());
				//}else{
				//	saleSkuPo.setMainCloudPath(saleSkuPo.getSaleEntityPo().getMainCloudPath());
				//}
				//获取产品媒体
				List<ProductMediaPo> productMediaPos = new ArrayList<ProductMediaPo>();
				if(productMediaPo!=null){
					productMediaPo.setSpecialValue("main");
					productMediaPos.add(productMediaPo);	
				}
				else{
					productMediaPo = new ProductMediaPo();
					productMediaPo.setSpecialValue("main");
					productMediaPos.add(productMediaPo);
				}
				//获取特殊尺寸
				List<ProductMediaPo> specialList = productMediaRepository.findSpecialMediaPoByProdIdAttrOpId(prodId, attrOpId);
				for(ProductMediaPo productMediaPo2:specialList){
					productMediaPos.add(productMediaPo2);
				}
				saleSkuPo.setProductMediaPoList(productMediaPos);
				
			}else{
				List<ProductMediaPo> productMediaPos = new ArrayList<ProductMediaPo>();
				ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdId(prodId);
				if(productMediaPo!=null){
					saleSkuPo.setProductMediaPo(productMediaPo);
					productMediaPo.setSpecialValue("main");
					productMediaPos.add(productMediaPo);
				} 
				else{
					productMediaPo = new ProductMediaPo();
					productMediaPo.setSpecialValue("main");
					productMediaPos.add(productMediaPo);
				}
				/*productMediaPo = productMediaRepository.getSpecialMediaPoByProdId(prodId);
				if(productMediaPo!=null) {
					saleSkuPo.setMainCloudPath(productMediaPo.getCloudPath());
				}else{
					saleSkuPo.setMainCloudPath(saleSkuPo.getSaleEntityPo().getMainCloudPath());
				}*/
				//获取产品媒体
				
			
				//获取特殊尺寸
				List<ProductMediaPo> specialList = productMediaRepository.findSpecialMediaPoByProdId(prodId);
				for(ProductMediaPo productMediaPo2:specialList){
					productMediaPos.add(productMediaPo2);
				}
				saleSkuPo.setProductMediaPoList(productMediaPos);
			}
			
		}else{
			List<ProductMediaPo> productMediaPos = new ArrayList<ProductMediaPo>();
			ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdId(prodId);
			if(productMediaPo!=null) 
				{
					saleSkuPo.setProductMediaPo(productMediaPo);
					productMediaPo.setSpecialValue("main");
					productMediaPos.add(productMediaPo);
				}
			else{
				productMediaPo = new ProductMediaPo();
				productMediaPo.setSpecialValue("main");
				productMediaPos.add(productMediaPo);
			}
			
			//获取特殊尺寸
			List<ProductMediaPo> specialList = productMediaRepository.findSpecialMediaPoByProdId(prodId);
			for(ProductMediaPo productMediaPo2:specialList){
				productMediaPos.add(productMediaPo2);
			}
			saleSkuPo.setProductMediaPoList(productMediaPos);
		}
		//获取特殊图
		//FIXME 特殊图

		
		//获取各种统计数量
		SaleEntityStatPo skuSaleEntityStatPo =saleEntityStatRepository.getByProdId(saleSkuPo.getSaleProdId());
		/*Integer totalRecords = saleReviewRepository.countSaleReviewForFront(
				"", "", saleSkuPo.getSaleEntityPo().getSaleId(), null, "all");	*/
		Integer totalRecords = 0;
		if(null!=skuSaleEntityStatPo){
			skuSaleEntityStatPo.setEvalQty(totalRecords);
			saleSkuPo.setSaleEntityStatPo(skuSaleEntityStatPo);
		}else {
			saleSkuPo.setSaleEntityStatPo( new SaleEntityStatPo());
		}
		
		//获取SKU的标签信息
		List<SaleSkuTagPo> saleSkuTagPos = saleSkuTagRepository.findBySkuId(saleSkuPo.getId());
		saleSkuPo.setSaleSkuTagPos(saleSkuTagPos);
		
		//获取sku分类信息 
		List<ProdCatePo> prodList = prodCateRepository.getProdCateWithCateList(prodId);// READ UNCOMMITTED (for I couldn't find any other good idea)
		saleSkuPo.setProdCatePos(prodList);
	}
	@Override
	public void getMainSkuCloudPath(SaleSkuPo saleSkuPo, String callType) {
		String picType="medium";
		getMainSkuCloudPath(saleSkuPo, callType,picType);
	}
	public List<SaleSkuPo> findForSelectorPaged(Map<String, Object> params,
			Page page) {
		// TODO Auto-generated method stub
		List<SaleSkuPo> saleSkuPos = saleSkuRepository.findForSelectorPaged(params, page);
		for(SaleSkuPo saleSkuPo:saleSkuPos){
			getMainSkuCloudPath(saleSkuPo, "", "");
		}
		return saleSkuPos;
	}
	/**
	 * TODO方法名称描述
	 * @param buildMap
	 * @param page
	 * @return 
	 * List<SaleSkuPo>
	 * @exception 
	 * @since  1.0.0
	 */
	public List<SaleSkuPo> listSkuMsg(Map<String, Object> buildMap, Page page) {
		List<SaleSkuPo> saleSkuPos = saleSkuRepository.listSkuMsg(buildMap, page);
		for(SaleSkuPo saleSkuPo:saleSkuPos){
			getMainSkuCloudPath(saleSkuPo, "web", "");
		}
		return saleSkuPos;
	}
	@Override
	public String getSkuIdByProdId(String prodId) {
		
		String skuId="";
		SaleSkuPo saleSkuPo = saleSkuQueryDao.getSkuIdByProdId(prodId);
		if(saleSkuPo!=null)skuId = saleSkuPo.getId();
		return skuId;
	}
	
	@Override
	public BigDecimal calPriceForPromo(String memberId, String skuId, String fromType) {

		BigDecimal salePrice = BigDecimal.ZERO;
		/*List<SkuRuleVo> skuRuleVos = new ArrayList<SkuRuleVo>();
		SalePricePo salePricePo = null;
		
		//判断是否有内购价
		Party party = partyRepository.load(memberId);
		if(party != null && "Y".equals(party.getData().getIsIn())){
			salePricePo = salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.IN_PRICE);
		}
		if(salePricePo != null && new Date().after(salePricePo.getFromTime()) && new Date().before(salePricePo.getToTime())){
			salePrice = new BigDecimal(salePricePo.getPrice());
		}else{
			if("web".equals(fromType)){
				salePricePo = salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.SALES_PRICE);
			}else{
				salePricePo = salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.MOBILE);
				if(salePricePo==null){
					salePricePo=salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.SALES_PRICE);
				}
			}
			
			if(salePricePo != null){
				salePrice = new BigDecimal(salePricePo.getPrice());
				SkuRuleVo skuRuleVo = new SkuRuleVo(skuId, 1, new BigDecimal(salePricePo.getPrice()), "buy_now", "");
				skuRuleVos.add(skuRuleVo);
				
				List<PromotionResult> promotionResults = promotionService.calcForSku(memberId, skuRuleVos);
				for (PromotionResult promotionResult : promotionResults) {
					if (promotionResult.hasProfit()) {
						RuleResult ruleResult = promotionResult.getRuleResult();
						salePrice = doRuleResult(ruleResult, salePrice);
						break;
					}
				}
			}
		}*/


		return salePrice;
	
	}
	
	@Override
	public boolean checkPromo(String memberId, String skuId, String fromType) {

		/*List<SkuRuleVo> skuRuleVos = new ArrayList<SkuRuleVo>();
		SalePricePo salePricePo = null;
		
		//判断是否有内购价
		Party party = partyRepository.load(memberId);
		if(party != null && "Y".equals(party.getData().getIsIn())){
			salePricePo = salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.IN_PRICE);
			if(salePricePo != null && new Date().after(salePricePo.getFromTime()) && new Date().before(salePricePo.getToTime())){
				return true;
			}
		}
		
		if("web".equals(fromType)){
			salePricePo = salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.SALES_PRICE);
		}else{
			salePricePo = salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.MOBILE);
			if(salePricePo==null){
				salePricePo=salePriceRepository.getByProdSkuType(skuId, SaleConstants.PRICE_TYPE.SALES_PRICE);
			}
		}
		
		if(salePricePo != null){
			SkuRuleVo skuRuleVo = new SkuRuleVo(skuId, 1, new BigDecimal(salePricePo.getPrice()), "buy_now", "");
			skuRuleVos.add(skuRuleVo);
			
			List<PromotionResult> promotionResults = promotionService.calcForSku(memberId, skuRuleVos);
			for (PromotionResult promotionResult : promotionResults) {
				if (promotionResult.hasProfit()) {
					return  true;
				}
			}
		}*/
		return false;
	}	
	
/*	private BigDecimal doRuleResult(RuleResult ruleResult, BigDecimal salePrice_) {
		BigDecimal salePrice = salePrice_;
		if(ruleResult.getSkuRuleVos() != null && ruleResult.getSkuRuleVos().size() > 0){
			if (ruleResult.getProfitType().equals(RuleConstants.PROFIT_TYPE.PERCENT) || ruleResult.getProfitType().equals(RuleConstants.PROFIT_TYPE.SKU_PERCENT)) {
				
				salePrice = ruleResult.getSkuRuleVos().get(0).getDiscountPrice();
				
			}else if (ruleResult.getProfitType().equals(RuleConstants.PROFIT_TYPE.DISCOUNT)) {
				
				salePrice = ruleResult.getSkuRuleVos().get(0).getDiscountPrice();
				
			}
		}
		
		return salePrice;
	}*/

	
}
